package com.odontosis.relatorio.conveniopolicia;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Properties;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;
import com.odontosis.entidade.Mes;
import com.odontosis.entidade.Procedimento;
import com.odontosis.entidade.ServicoConveniado;
import com.odontosis.rel.RelatorioUtil;
import com.odontosis.service.ServicoConveniadoService;
import com.odontosis.util.StringUtilsOdontosis;
import com.odontosis.view.OdontosisAction;

public class AcaoRelatorioPolicia extends OdontosisAction<ServicoConveniadoService> {
	
	/**
	 * Mtodo principal da ao. 
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormRelatorioPolicia formRelatorio = (FormRelatorioPolicia) actionForm;

		return super.execute(mapping, actionForm, request, response);
	}
	
	public ActionForward vizualizar(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		FormRelatorioPolicia formRelatorio = (FormRelatorioPolicia) actionForm;
		SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
		Calendar inicio = Calendar.getInstance();
		inicio.setTime(formato.parse(formRelatorio.getDataInicio()));
		inicio.set(Calendar.HOUR, 0);
		inicio.set(Calendar.MINUTE, 0);
		inicio.set(Calendar.SECOND, 0);
		
		Calendar fim = Calendar.getInstance();
		fim.setTime(formato.parse(formRelatorio.getDataFim()));
		fim.set(Calendar.HOUR, 23);
		fim.set(Calendar.MINUTE, 59);
		fim.set(Calendar.SECOND, 59);
		
		gerarRelatorio(inicio.getTime(), fim.getTime() , formRelatorio.getCodigoProcedimento(), response);
		
		return null;
	}
	
	
	public void gerarRelatorio(Date inicio, Date fim, String codigoProcedimento, HttpServletResponse response){
		try{
			//fontes
			Font fontItem = new Font(Font.HELVETICA, 10, Font.NORMAL);
	        Font fontTotal = new Font(Font.HELVETICA, 10, Font.BOLD);
	        Font fonteTitulo = new Font(Font.HELVETICA, 11, Font.BOLD);
	        Font fonteCabecalho = new Font(Font.HELVETICA, 13, Font.BOLD);
	        
			//inicializa documento
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			Document document = new Document();
			PdfWriter.getInstance(document, baos);
			document.open();
			
			Collection<ServicoConveniado> resultado = service.pesquisarPorDataECodigoSemPericia(inicio, fim, codigoProcedimento);
			
			//define o titulo
			SimpleDateFormat formata = new SimpleDateFormat("dd/MM/yyyy");
			String dataInicio = formata.format(inicio.getTime());
			String dataFim = formata.format(fim.getTime());
			
			String periodo =  dataInicio + " até "+ dataFim;
			Paragraph paragrafoTitulo = new Paragraph(new Phrase("Relatório dos Conveniados à Polícia Militar sem Data de Perícia\n  "+periodo, fonteCabecalho));
            paragrafoTitulo.setAlignment(1);
            document.add(paragrafoTitulo);
			
			//cria a tabela
			float [] tamanhos = {1,3,1,2,2,1};
			Table table = criarObjetoTabela(6, tamanhos);
			Cell t1 = new Cell(new Phrase("N. IPSM", fonteCabecalho));
			t1.setBackgroundColor(new Color(236, 235, 234));    
			table.addCell(t1);
			
			Cell t2 = new Cell(new Phrase("Paciente", fonteCabecalho));
			t2.setBackgroundColor(new Color(236, 235, 234));
			table.addCell(t2);
			
			Cell t3 = new Cell(new Phrase("FIOD", fonteCabecalho));
			t3.setBackgroundColor(new Color(236, 235, 234));
			table.addCell(t3);
			
			Cell t5 = new Cell(new Phrase("Data/Parcela", fonteCabecalho));
			t5.setBackgroundColor(new Color(236, 235, 234));
			table.addCell(t5);
			
			Cell t4 = new Cell(new Phrase("Código", fonteCabecalho));
			t4.setBackgroundColor(new Color(236, 235, 234));
			table.addCell(t4);
			
			Cell t6 = new Cell(new Phrase("Valor", fonteCabecalho));
			t6.setBackgroundColor(new Color(236, 235, 234));
			table.addCell(t6);
			double total = 0.0;
			for (ServicoConveniado servico : resultado) {
				for(Procedimento procedimento : servico.getListaProcedimentos()){
				    int rowspan = servico.getListaProcedimentos().size();
					Cell ipsm = new Cell(new Phrase(servico.getPaciente().getIpsm(), fontItem));
					//ipsm.setRowspan(rowspan);
					table.addCell(ipsm);
					
					Cell paciente = new Cell(new Phrase(servico.getPaciente().getNome(), fontItem));
					//paciente.setRowspan(rowspan);
					table.addCell(paciente);
					
					Cell fiod = new Cell(new Phrase(servico.getFiod(), fontItem));
					//fiod.setRowspan(rowspan);
					table.addCell(fiod);
					
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(servico.getData());
					int mesInteiro = calendar.get(Calendar.MONTH) + 1;
					int ano = calendar.get(Calendar.YEAR);
					Mes mes = Mes.recuperarPorId(mesInteiro);
					String parcela = servico.getParcela() == 0 ? "única" : servico.getParcela().toString();
					
					Cell manut = new Cell(new Phrase(mes.getAbreviacao() + "/" +ano+ " - "+parcela, fontItem));
					//manut.setRowspan(rowspan);
					table.addCell(manut);
					
				
					Cell codigo = new Cell(new Phrase(procedimento.getCodigo(), fontItem));
					table.addCell(codigo);
					
					Cell valor = new Cell(new Phrase(StringUtilsOdontosis.formatarDouble(procedimento.getValor()), fontItem));
					table.addCell(valor);
					total += procedimento.getValor();
				}
				
			}
			
			Cell rodape = new Cell(new Phrase("Total"));
			rodape.setColspan(5);
			rodape.setBackgroundColor(new Color(236, 235, 234));    
			table.addCell(rodape);
			
			Cell totaliza = new Cell(new Phrase(StringUtilsOdontosis.formatarDouble(total),fontTotal));
			totaliza.setBackgroundColor(new Color(236, 235, 234));    
			table.addCell(totaliza);
			
			
			
			document.add(table);
			inserirRodaPe(document);
			document.close();
			response.setContentType("application/pdf");
			response.setContentLength(baos.size());
			ServletOutputStream out = response.getOutputStream();
			baos.writeTo(out);
			out.flush();
			
		
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void inserirRodaPe(Document documento) throws Exception{
		documento.add(new Paragraph("\n"));
		documento.add(new Paragraph(new Phrase("Ortodontista Núcleo Odontológico Especializado Dr. Rogério Alves Batista",RelatorioUtil.fontTotal)));
		documento.add(new Paragraph(""));
		
		documento.add(new Paragraph(new Phrase("Data: " + StringUtilsOdontosis.DateToString(new Date()),RelatorioUtil.fonteRodape)));
		documento.add(new Paragraph("\n"));
		documento.add(new Paragraph(new Phrase("______________________________________   ______________________________________________",RelatorioUtil.fontItem)));
		documento.add(new Paragraph(new Phrase("CARIMBO E ASSINATURA DO CONVENIADO   CARIMBO E ASSINATURA DO AUX. DA ORTODONTIA",RelatorioUtil.fontItem)));

	}
	
	private Table criarObjetoTabela(int numColunas, float[] headerWidths) {
	        try {
	            Table aTable = new Table(numColunas);

	            aTable.setPadding(1);
	            aTable.setSpacing(0);

	            aTable.setWidths(headerWidths);

	            aTable.widthPercentage();
	            aTable.setWidth(100);
	            aTable.setBorder(0);

	            aTable.setSpaceBetweenCells(0);

	            aTable.setDefaultCellBorderWidth(0);
	            aTable.setBorder(0);

	            return aTable;
	        } catch (BadElementException e) {
	            throw new RuntimeException("Erro definindo largura do cabeçalho", e);
	        }
	    }

}
